package com.asktgapp.user.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.asktgapp.JGTool.EmojiFilter;
import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.model.AddIMGVO;
import com.asktgapp.model.ImgUrlVO;
import com.asktgapp.modulebase.ServiceUtil;
import com.asktgapp.modulebase.common.adapter.BaseAdapter;
import com.asktgapp.modulebase.common.adapter.BaseViewHolder;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.utils.ImageDisplayUtil;
import com.asktgapp.utils.SelectPhotoDialogFragment;
import com.jph.takephoto.model.TImage;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * time:2018-7-21 18:11:35
 * Description:投诉工程师页面
 */

public class ComplaintEngineerFragment extends BaseFragment {
    private EditText mQuestion;
    private TextView tvTextNumber, myToolbarRight, myBack,userName;
    private List allURls = new ArrayList();//所有要展示的url
    private List<ImgUrlVO> imgUrl;
    private int IMGWidth;
    private BaseAdapter mBaseAdapter;
    private RecyclerView mPhotoRecyclerView;
    private ImageView head ;
    private String engineerId,messageCid;
    private String mAskName;
    private String mAskEngineerHead;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_complaint_engineer, container, false);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {
        getBaseActivity().getToolbar().setVisibility(View.GONE);
        setHasOptionsMenu(true);
        Intent intent = getActivity().getIntent();
        engineerId = intent.getStringExtra("eg_user_id");
        mAskName = intent.getStringExtra("name");
        messageCid = intent.getStringExtra("messageCid");
        mAskEngineerHead = intent.getStringExtra("userpic");
        WindowManager windowManager = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        IMGWidth = display.getWidth() / 5;

        mQuestion = rootView.findViewById(R.id.et_question);
        mPhotoRecyclerView = rootView.findViewById(R.id.recycle_photo);
        myToolbarRight = rootView.findViewById(R.id.myToolbarRight);
        myBack = rootView.findViewById(R.id.myBack);
        tvTextNumber = rootView.findViewById(R.id.tvTextNumber);
        head = rootView.findViewById(R.id.img);
        userName = rootView.findViewById(R.id.tv_conment_name);
        userName.setText(mAskName);
        ImageDisplayUtil.loadCircleHeadImage(getActivity(),head,mAskEngineerHead);
        mQuestion.setFilters(new InputFilter[]{new EmojiFilter()});
        imgUrl = new ArrayList();
        mPhotoRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        mQuestion.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                tvTextNumber.setText(String.valueOf(s.length()));
            }
        });
        myBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getBaseActivity().onBackPressed();
            }
        });


        myToolbarRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String question = mQuestion.getText().toString().trim();
                if(TextUtils.isEmpty(question)){
                    showTost("投诉内容不能为空！", 0);
                    return;
                }

                if (!Utils.noContainsEmoji(question)) {
                    showTost("不支持输入emoji表情", 1);
                    return;
                }
                hideSoftKeyboard();
                myToolbarRight.setClickable(false);
                doCommit();
            }
        });

        mBaseAdapter = new BaseAdapter(getActivity()) {
            @Override
            public BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {
                BaseViewHolder holder = null;
                if (viewType == 0) {
                    //本地图片
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_select_photo, parent, false), new BaseViewHolder.Callbacks() {
                        @Override
                        public void bind(BaseViewHolder holder, Object data) {
                            ImageView imageView = holder.getView(R.id.img);
                            final ImageView delete = holder.getView(R.id.iv_delete);
                            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
                            params.width = IMGWidth;
                            params.height = IMGWidth;
                            imageView.setLayoutParams(params);
                            if (data instanceof ImgUrlVO) {
                                final ImgUrlVO bean = (ImgUrlVO) data;
                                ImageDisplayUtil.LoadDisImage(getActivity(), imageView, bean.getUrl());
                                delete.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        imgUrl.remove(bean);
                                        setAdpterData();
                                    }
                                });
                            }
                        }

                        @Override
                        public void onItemClick(View view, int position) {

                        }
                    });
                } else if (viewType == 1) {
                    //添加
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_picture_add, parent, false), new BaseViewHolder.Callbacks() {
                        @Override
                        public void bind(BaseViewHolder holder, Object data) {
                            ImageView imageView = holder.getView(R.id.img);
                            FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) imageView.getLayoutParams();
                            params.width = IMGWidth;
                            params.height = IMGWidth;
                            imageView.setLayoutParams(params);
                        }

                        @Override
                        public void onItemClick(View view, int position) {
                            onPickPhoto();

                        }
                    });
                }
                return holder;

            }

            @Override
            public int getItemViewType(int position) {
                Object bean = mBaseAdapter.getData().get(position);
                if (bean instanceof ImgUrlVO) {
                    return 0;
                } else if (bean instanceof AddIMGVO) {
                    return 1;
                } else return 0;

            }
        };
        mPhotoRecyclerView.setAdapter(mBaseAdapter);
        setAdpterData();

    }

    private void onPickPhoto() {
        SelectPhotoDialogFragment selectPhotoDialogFragment = new SelectPhotoDialogFragment(new SelectPhotoDialogFragment.setResult() {
            @Override
            public void setResult(ArrayList<TImage> mImages) {
                for (TImage img : mImages) {
                    ImgUrlVO bean = new ImgUrlVO(img.getPath());
                    imgUrl.add(bean);
                }
                setAdpterData();
            }
        }, 3 - imgUrl.size());
        selectPhotoDialogFragment.show(getFragmentManager(), "selectPhotoDialogFragment");
    }

    public void setAdpterData() {
        allURls.clear();
        if (imgUrl.size() > 0) {
            allURls.addAll(imgUrl);
        }
        mBaseAdapter.setData(allURls);
        if (allURls.size() < 3) {
            mBaseAdapter.addData(BaseAdapter.AddType.LASE, new AddIMGVO());
        }
    }
    private void doCommit() {
        myToolbarRight.setClickable(false);
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        ApiUtil.putDefultData(getActivity(), params);
//        params.put("price", RequestBody.create(ServiceUtil.MULTIPART, mPriceET.getText().toString().trim()));
//        params.put("typeId", RequestBody.create(ServiceUtil.MULTIPART, mSelectedTypeId));
        params.put("userId", RequestBody.create(ServiceUtil.MULTIPART, PreferencesUtil.getString(getContext(), PreferencesUtil.USER_ID)));
        params.put("targetId", RequestBody.create(ServiceUtil.MULTIPART,engineerId ));
        params.put("page", RequestBody.create(ServiceUtil.MULTIPART,"1"));
        params.put("reason", RequestBody.create(ServiceUtil.MULTIPART,mQuestion.getText().toString().trim()));
        List<String> url = new ArrayList<>();
        for (ImgUrlVO vo : imgUrl) {
            url.add(vo.getUrl());
        }
        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody> call = apiservice.complaint(params, ApiUtil.files2Parts("complaintPic", url.toArray(), ApiUtil.MULTIPART));
        call.enqueue(new Callback<ApiResponseBody>() {
            @Override
            public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                myToolbarRight.setClickable(true);
                if (response.isSuccessful()) {
                    showTost("投诉提交成功", 0);
                    PreferencesUtil.putString(getActivity(), "touSofCid"+messageCid,messageCid);
                    getActivity().finish();
                } else {
                    showTost(response.raw().message(), 1);
                    myToolbarRight.setClickable(true);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                myToolbarRight.setClickable(true);
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }

            }
        });

    }

    @Override
    public void loadData() {

    }


}
